package util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import org.junit.Test;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.data.Data;

/**
* @author 作者:秋哲    E-mail:2810201146@qq.com:
* @version 创建时间：2020年4月28日 下午3:27:38
* @description: JDBC工具类基于Util工具类和Druid连接池
*/
public class JDBCUtiles {
	private static DataSource source;
	static {
		Properties pros = new Properties();
		String path = "durid.properties";
		if(Data.config.DBUG) {
			path = "duridDBUG.properties";
		}
		InputStream is = JDBCUtiles.class.getClassLoader().getResourceAsStream(path);
		try {
			pros.load(is);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		try {
			source = DruidDataSourceFactory.createDataSource(pros);
		} catch (Exception e
				) {
			e.printStackTrace();
		}
	}
	/**
	 * 
	 * @version 创建时间：2020年4月28日 下午3:30:58
	 * @description  获取 Connection 连接
	 * @return
	 * @throws Exception
	 */
	
	public static Connection getConnection() throws Exception {
		Connection connection = source.getConnection();
		return connection;
	}

	public static void main(String[] args) {
		try {
			Connection conn = getConnection();
			System.out.println(conn);
			closeResource(conn);			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void testConnection() {
		try {
			Connection conn = getConnection();
			System.out.println(conn);
			closeResource(conn);			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void closeResource(Connection conn) {
		try {
			if(conn!=null)
				conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public static void closeResource(Connection conn,Statement ps) {
		try {
			if(ps!=null)
			ps.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if(conn!=null)
				conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public static void closeResource(Connection conn,Statement ps,ResultSet rs) {
		try {
			if(ps!=null)
			ps.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if(conn!=null)
				conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if(rs!=null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
